#include <REGX52.H>
#include "Timer0.h"
#include "Int0.h"

typedef enum {
    IR_IDLE,      // 空闲状态
    IR_READY,     // 等待数据
    IR_RECEIVING, // 接收数据
} IR_State;

IR_State state = IR_IDLE;
// 接收到的数据 0->4 : 地址 地址的反码 命令 命令的反码
unsigned char buffer[4];
// 重复按键标志位
unsigned char repeatFlag = 0;
// 接收到红外标志位
unsigned char receivedFlag = 0;
// 接收到的红外地址
unsigned char address;
// 接收到的红外命令
unsigned char command;

/**
 * @brief 初始化红外接收模块
 */
void IR_Init()
{
    Timer0_Init();
    Timer0_Enable(0);
    Timer0_SetCounter(0);
    INT0_Init();
}

/**
 * @brief 获取红外接收模块的接收标志位
 * @return 接收到红外返回1，否则返回0
 */
unsigned char IR_GetReceivedFlag()
{
    if (receivedFlag) {
        receivedFlag = 0;
        return 1;
    }
    return 0;
}

/**
 * @brief 获取红外模块的重复标志位
 * @return 重复接收到红外返回1，否则返回0
 */
unsigned char IR_GetRepeatFlag()
{
    if (repeatFlag) {
        repeatFlag = 0;
        return 1;
    }
    return 0;
}

/**
 * @brief 获取红外模块接收到的地址
 * @return 接收到的地址
 */
unsigned char IR_GetAddress()
{
    return address;
}

/**
 * @brief 获取红外模块接收到的命令
 * @return 接收到的命令
 */
unsigned char IR_GetCommand()
{
    return command;
}

/*
 * 中断服务程序
 */
void INT0_Isr(void) interrupt 0
{
    static unsigned char bitPointer = 0;
    unsigned int counter;

    if (state == IR_IDLE) {
        state = IR_READY;
        Timer0_SetCounter(0);
        Timer0_Enable(1);

    } else if (state == IR_READY) {
        counter = Timer0_GetCounter();
        Timer0_SetCounter(0);

        // 判断是Start还是Repeat
        // 12442 - 500 && 12442 + 500, Start
        if (counter > 11942 && counter < 12942) {
            state = IR_RECEIVING;

            // 10368 - 500 && 10368 + 500, Repeat
        } else if (counter > 9868 && counter < 10868) {
            repeatFlag = 1;
            state      = IR_IDLE;
            Timer0_Enable(0);
        } else {
            // 出错
            state = IR_IDLE;
            Timer0_Enable(0);
        }

    } else if (state == IR_RECEIVING) {
        counter = Timer0_GetCounter();
        Timer0_SetCounter(0);

        // 开始接收数据
        // 1032 - 500 && 1032 + 500, 数据0
        if (counter > 532 && counter < 1532) {
            buffer[bitPointer / 8] &= ~(0x01 << (bitPointer % 8));
            bitPointer++;

            // 2074 - 500 && 2074 + 500, 数据1
        } else if (counter > 1574 && counter < 2574) {
            buffer[bitPointer / 8] |= (0x01 << (bitPointer % 8));
            bitPointer++;
        } else {
            // 出错
            state = IR_IDLE;
            Timer0_Enable(0);
            bitPointer = 0;
        }

        // 已经接受好32位数据
        if (bitPointer >= 32) {
            state = IR_IDLE;
            Timer0_Enable(0);
            bitPointer = 0;
            if (buffer[0] == ~buffer[1] && buffer[2] == ~buffer[3]) {
                // 数据校验通过
                address      = buffer[0];
                command      = buffer[2];
                receivedFlag = 1;
            }
        }
    }
}